﻿Imports System
Imports System.IO
Imports System.Text

Public Class RoughProcess

    Public Func As Functions = New Functions
    Dim FeatureType As Integer
    Dim ToolSettingForm As ToolSettingForm = New ToolSettingForm

    Dim QueryFeatureCode As Integer

    '加工情報の宣言------------------------------------------------------------------------------------------------------
    Public Property OperationName As String = "N/A"
    Public Property MachiningType As Integer = 0
    '1:フェースミル加工 2:輪郭加工 3:ポケット加工 4:ドリル加工 5:スパイラル加工 6:その他（割り当てられていない加工）
    Public Property ToolID As String = "N/A"
    Public Property SpindleSpeed As Long = 0
    Public Property XYFeedrate As Double = 0
    Public Property ZFeedrate As Double = 0
    Public Property MachiningMode As Integer = 0
    'FaceMill:
    '   1: 一方向  2:双方向
    'PockettMill:
    '   0:一方向   1:Zig-Zag   2:同心-In   3:同心-Out
    'CountourMill:
    '   1:DepthFirst    2:Widthfirst
    'SpiralMill:
    '   0:内から外  1:外から内
    Public Property StepOver As Double = 2
    Public Property TotalDepth As Double = 0
    Public Property IncrementalDepth As Double = 0
    Public Property StartingDepth As Double = 0
    Public Property MachiningStrategy As Integer = 0
    '0:アップカット   1:ダウンカット
    Public Property PassesNum As Integer = 0
    Public Property StockAllowanceWall As Double
    Public Property StockAllowanceFloor As Double

    '素材形状の宣言------------------------------------------------------------------------------------------------------
    Dim MaterialXMax, MaterialXMin, MaterialYMax, MaterialYMin, MaterialZMax, MaterialZMin As Double
    Dim Point(10, 2) As Double
    Dim MarginXY As Double

    '製品形状の宣言------------------------------------------------------------------------------------------------------
    Dim ShapeXMax, ShapeXMin, ShapeYMax, ShapeYMin, ShapeZMax, ShapeZMin As Double
    Dim Depth As Double

    '検索対象のモデルの情報の宣言-----------------------------------------------------------------------------------------
    Public gDBModelCode(100) As Integer
    Public gDBFeatureCode(100) As Integer
    Public gMatchNum As Integer

    '使用できる工具の判定
    Dim IsUsableFaceMill As Boolean = True
    Dim IsUsableSquareEndMill As Boolean = True
    Dim IsUsableBallEndMill As Boolean = True
    Dim IsUsableDrill As Boolean = True


    '各種類似度の宣言
    Dim TotalSimilarity(100) As Double      '総合類似度
    Dim ShapeSimilarity(100) As Double      '形状類似度
    Dim SizeSimilarity(100) As Double       '寸法類似度
    Dim ReferencedRate(100) As Double       '被引用度
    Dim MaterialSimilarity(100) As Double   '素材類似度
    Dim ToolUsability(100) As Boolean       '工具引用可能性

    Dim ToolName(100) As String             '工具ID
    Dim ToolType(100) As Integer            '工具の種類（1:フェースミル/2:スクウェアエンドミル/3:ボールエンドミル）
    Dim ToolDiameter(100) As Double         '工具系
    Dim CuttingLength(100) As Double        '有効刃長
    Dim ToolLength(100) As Double           '工具長
    Dim FlutesNum(100) As Integer           '刃数
    Dim ToolMaterial(100) As Integer        '工具素材（1:カーバイド/2:CBN/3:セラミック/4:HSS）
    Dim Coating(100) As Integer             'コーティング素材（1:あり/0:なし）
    Dim RestrictingLength As Double
    Dim tRestrictingLength As Double

    '使用した工具の情報---------------------------------------------------------------------------------------------------
    Public Property usedToolType As Integer
    Public Property usedToolDiameter As Double

    '工具径の制限
    Public Sub Restricting(ByVal RLength As Double)
        tRestrictingLength = RLength
    End Sub

    'test

    '起動前に読み込む関数（素材形状を読み込み，認識/工具情報を読み込み，リストを作成）
    Public Sub PreLoardForm(ByVal Code As Integer)
        Dim path As String
        Dim Read As StreamReader
        Dim Reader As String
        Dim FeatureNum, FeatureCounter As Integer
        Dim PointNum, PointCounter As Integer
        Dim retval(5) As String
        Dim flag As Boolean = False
        Dim FeatureCode As Integer

        QueryFeatureCode = Code

        '素材形状を読み込み
        path = "MaterialShape.txt"
        Read = New StreamReader(path)
        Reader = Read.ReadLine
        retval = Reader.Split(CChar(" "))
        MaterialXMax = CDbl(retval(0))
        MaterialYMax = CDbl(retval(1))
        MaterialZMax = CDbl(retval(2))
        MaterialXMin = CDbl(retval(3))
        MaterialYMin = CDbl(retval(4))
        MaterialZMin = CDbl(retval(5))

        '製品形状を読み込み（対象のFeatureChainKeyのみ）
        flag = False
        path = "ShapeDataEsp.txt"
        Read = New StreamReader(path)

        Reader = Read.ReadLine
        retval = Reader.Split(CChar(" "))
        FeatureNum = CInt(retval(0))

        For FeatureCounter = 0 To FeatureNum - 1
            If flag Then Exit For

            Reader = Read.ReadLine
            retval = Reader.Split(CChar(" "))
            FeatureType = CInt(retval(1))

            Reader = Read.ReadLine
            retval = Reader.Split(CChar(" "))
            FeatureCode = CInt(retval(0))
            PointNum = CInt(retval(2))

            For PointCounter = 0 To PointNum - 1

                Reader = Read.ReadLine
                retval = Reader.Split(CChar(" "))

                '対象のFeatureChain であれば，座標の情報の取得
                If FeatureCode = Code Then
                    flag = True
                    Point(PointCounter, 0) = CDbl(retval(0))
                    Point(PointCounter, 1) = CDbl(retval(1))
                    Point(PointCounter, 2) = CDbl(retval(2))
                End If
            Next
            Reader = Read.ReadLine
            retval = Reader.Split(CChar(" "))
            If FeatureCode = Code Then
                Depth = CDbl(retval(0))
            End If
        Next

        '製品形状の最大値を設定
        '最初は，0番目の点を取得
        ShapeXMax = Point(0, 0)
        ShapeXMin = Point(0, 0)
        ShapeYMax = Point(0, 1)
        ShapeYMin = Point(0, 1)
        ShapeZMax = Point(0, 2)
        ShapeZMin = Point(0, 2)
        'i番目の点がMaxよりも大きい/Minよりも小さい場合は値の入れ替え
        For i As Integer = 1 To PointNum - 1
            If ShapeXMax < Point(i, 0) Then ShapeXMax = Point(i, 0)
            If ShapeXMin > Point(i, 0) Then ShapeXMin = Point(i, 0)
            If ShapeYMax < Point(i, 1) Then ShapeYMax = Point(i, 1)
            If ShapeYMin > Point(i, 1) Then ShapeYMin = Point(i, 1)
            If ShapeZMax < Point(i, 2) Then ShapeZMax = Point(i, 2)
            If ShapeZMin > Point(i, 2) Then ShapeZMin = Point(i, 2)
        Next
        MarginXY = 0
        If MarginXY < ((MaterialXMax - ShapeXMax) ^ 2 + (MaterialYMax - ShapeYMax) ^ 2) ^ (1 / 2) Then MarginXY = ((MaterialXMax - ShapeXMax) ^ 2 + (MaterialYMax - ShapeYMax) ^ 2) ^ (1 / 2)
        If MarginXY < ((MaterialXMax - ShapeXMax) ^ 2 + (MaterialYMin - ShapeYMin) ^ 2) ^ (1 / 2) Then MarginXY = ((MaterialXMax - ShapeXMax) ^ 2 + (MaterialYMin - ShapeYMin) ^ 2) ^ (1 / 2)
        If MarginXY < ((MaterialXMin - ShapeXMin) ^ 2 + (MaterialYMax - ShapeYMax) ^ 2) ^ (1 / 2) Then MarginXY = ((MaterialXMin - ShapeXMin) ^ 2 + (MaterialYMax - ShapeYMax) ^ 2) ^ (1 / 2)
        If MarginXY < ((MaterialXMin - ShapeXMin) ^ 2 + (MaterialYMin - ShapeYMin) ^ 2) ^ (1 / 2) Then MarginXY = ((MaterialXMin - ShapeXMin) ^ 2 + (MaterialYMin - ShapeYMin) ^ 2) ^ (1 / 2)

        If Func.IsUpSideOrNot(FeatureType) Then
            ShapeZMax += Depth
        Else
            ShapeZMin -= Depth
        End If

        Dim ToolCounter As Integer = 0


        path = "ToolInfo.txt"
        Dim ReadTool As IO.StreamReader = New StreamReader(path)
        While Not ReadTool.Peek = -1
            Reader = ReadTool.ReadLine()
            retval = Reader.Split(CChar("/"))

            ToolName(ToolCounter) = retval(0)
            ToolType(ToolCounter) = CInt(retval(1))
            ToolDiameter(ToolCounter) = CDbl(retval(2))
            CuttingLength(ToolCounter) = CDbl(retval(3))
            ToolLength(ToolCounter) = CDbl(retval(4))
            FlutesNum(ToolCounter) = CInt(retval(5))
            ToolMaterial(ToolCounter) = CInt(retval(6))
            Coating(ToolCounter) = CInt(retval(7))

            ToolCounter += 1
        End While

        If FeatureType = 1 Or FeatureType = 3 Or FeatureType = 4 Or FeatureType = 5 Or FeatureType = 7 Or FeatureType = 8 Then
            RestrictingLength = tRestrictingLength
        End If
    End Sub

    '起動時に読み込む関数（イベントハンドラ）
    Private Sub DataReusingForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ShowSimilarShapeCandidate()
    End Sub

    '起動時に類似形状の候補を表示する
    Public Sub ShowSimilarShapeCandidate()
        ComboBoxInfo.Items.Clear()

        gMatchNum = 0
        For i = 0 To 99
            gDBModelCode(i) = 0
            gDBFeatureCode(i) = 0
            TotalSimilarity(i) = 0
            ShapeSimilarity(i) = 0
            SizeSimilarity(i) = 0
            MaterialSimilarity(i) = 0
        Next
        'Databaseから同じフィーチャを検索
        FindSameFeature()

        '形状類似度を計算
        CalShapeSimilarity()

        '寸法類似度を計算
        CalSizeSimilarity()

        '素材類似度を計算
        CalMaterialSimilarity()

        '引用率を計算
        CalReferenceRate()

        '工具使用可能性を計算
        CalToolUsability()

        '総合類似度を計算
        CalTotalSimilarity()

        '結果をソート
        BoubleSort()

        '結果の表示
        For MatchCount As Integer = 0 To gMatchNum - 1
            If TotalSimilarity(MatchCount) = 0 Then Exit For
            'MEMO 131111被引用率は非表示に
            'ComboBoxInfo.Items.Add("Similarity:" + TotalSimilarity(MatchCount).ToString("0.000") + " Model:" + CStr(ModelCode(MatchCount)) + "-" + CStr(FeatureCode(MatchCount)) + " Sim.Sh.:" + ShapeSimilarity(MatchCount).ToString("0.000") + " Sim.Si.:" + SizeSimilarity(MatchCount).ToString("0.000") + " R.Rate:" + ReferencedRate(MatchCount).ToString("0.000") + " Sim.M.:" + MaterialSimilarity(MatchCount).ToString("0.000"))
            ComboBoxInfo.Items.Add("Similarity:" + TotalSimilarity(MatchCount).ToString("0.000") + _
                                   " Model:" + CStr(gDBModelCode(MatchCount)) + "-" + CStr(gDBFeatureCode(MatchCount)) + _
                                   " Sim.Sh.:" + ShapeSimilarity(MatchCount).ToString("0.000") + _
                                   " Sim.Si.:" + SizeSimilarity(MatchCount).ToString("0.000") + _
                                   " Sim.M.:" + MaterialSimilarity(MatchCount).ToString("0.000"))
        Next

    End Sub

    '適応ボタンを押した時の挙動（イベントハンドラ）
    Private Sub ButtonApply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonApply.Click
        ReadMachiningData(gDBModelCode(CInt(ComboBoxInfo.SelectedIndex)), gDBFeatureCode(CInt(ComboBoxInfo.SelectedIndex)))
    End Sub

    '加工データを読み込んで表示
    Public Sub ReadMachiningData(ByVal RefModelCode As Integer, ByVal RefFeatureCode As Integer)
        '加工データの読み込み/表示

        '読み込み用のReader
        Dim path As String = "RoughProcess Database.csv"
        Dim Reader As StreamReader = New StreamReader(path)
        Dim Read As String
        Dim retval(20) As String
        Dim ModelCodeInDB As Integer
        Dim FeatureCodeInDB As Integer

        '表示する対象のモデルの情報を読み込み
        Read = Reader.ReadLine()
        Do
            Read = Reader.ReadLine()
            retval = Read.Split(CChar(","))
            ModelCodeInDB = CInt(retval(0))
            FeatureCodeInDB = CInt(retval(1))
            OperationName = retval(2)
            MachiningType = CInt(retval(3))
            ToolID = retval(4)
            SpindleSpeed = CLng(retval(5))
            XYFeedrate = CDbl(retval(6))
            ZFeedrate = CDbl(retval(7))
            MachiningMode = CInt(retval(8))
            StepOver = CDbl(retval(9))
            IncrementalDepth = CDbl(retval(10))
            TotalDepth = CDbl(retval(11))
            StartingDepth = CDbl(retval(12))
            MachiningStrategy = CInt(retval(13))
            PassesNum = CInt(retval(14))
            StockAllowanceWall = CDbl(retval(15))
            StockAllowanceFloor = CDbl(retval(16))
        Loop Until ModelCodeInDB = RefModelCode And FeatureCodeInDB = RefFeatureCode

        '表示する対象のモデルの情報を表示
        retval = Read.Split(CChar(","))
        ComboBoxMachiningType.SelectedIndex = MachiningType
        ButtonToolID.Text = ToolID
        TextBoxSpindleSpeed.Text = CStr(SpindleSpeed)
        TextBoxXYFeedrate.Text = CStr(XYFeedrate)
        TextBoxZFeedrate.Text = CStr(ZFeedrate)
        ComboBoxMachiningMode.Items.Clear()
        With ComboBoxMachiningMode
            Select Case MachiningType
                Case 1  'フェースミル加工
                    .Items.Add("")
                    .Items.Add("一方向")
                    .Items.Add("双方向")
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
                Case 2  '輪郭加工
                    .Items.Add("")
                    .Items.Add("深さ方向から")
                    .Items.Add("幅方向から")
                    TextBoxPassesNum.Enabled = True
                    Label17.Enabled = True
                Case 3  'ポケット加工
                    .Items.Add("一方向")
                    .Items.Add("ジグザグ")
                    .Items.Add("同心円-In")
                    .Items.Add("同心円-Out")
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
                Case 4  'ドリル加工
                    .Items.Add(" ")
                    Label6.Enabled = False
                    ComboBoxMachiningMode.Enabled = False
                    Label4.Enabled = False
                    TextBoxXYFeedrate.Enabled = False
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
                    TextBoxStepOver.Enabled = False
                    Label7.Enabled = False
                    TextBoxIncrementalDepth.Enabled = False
                    Label9.Enabled = False
                    ComboBoxMachiningStrategy.Enabled = False
                    Label12.Enabled = False
                    TextBoxStockAllowanceWall.Enabled = False
                    Label21.Enabled = False
                    TextBoxStockAllowanceFloor.Enabled = False
                    Label1.Enabled = False
                Case 5  'スパイラル加工
                    .Items.Add("内から外")
                    .Items.Add("外から内")
                    TextBoxStepOver.Enabled = False
                    Label7.Enabled = False
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
            End Select
            .SelectedIndex = MachiningMode
        End With
        TextBoxStepOver.Text = CStr(StepOver)
        TextBoxIncrementalDepth.Text = CStr(IncrementalDepth)
        TextBoxTotalDepth.Text = CStr(TotalDepth)
        TextBoxStartingDepth.Text = CStr(StartingDepth)
        ComboBoxMachiningStrategy.SelectedIndex = MachiningStrategy
        If MachiningType = 2 Then
            TextBoxPassesNum.Enabled = True
            Label17.Enabled = True
            TextBoxPassesNum.Text = CStr(PassesNum)
        Else
            Label17.Enabled = False
            TextBoxPassesNum.Text = "0"
            TextBoxPassesNum.Enabled = False
        End If
        TextBoxStockAllowanceWall.Text = CStr(StockAllowanceWall)
        TextBoxStockAllowanceFloor.Text = CStr(StockAllowanceFloor)


    End Sub

    '計算ボタンを押した時の挙動（イベントハンドラ）
    Private Sub ButtonCalDepth_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCalDepth.Click
        ReviseMachiningData()
    End Sub

    '加工データを新しい形状に合うように修正する
    Public Sub ReviseMachiningData()
        StockAllowanceWall = CDbl(TextBoxStockAllowanceWall.Text)
        StepOver = CDbl(TextBoxStepOver.Text)

        '輪郭加工であれば，パス数を計算（値を変更していれば，boxの背景色を変更）
        If MachiningType = 2 Then
            PassesNum = CInt(Math.Ceiling((MarginXY - StockAllowanceWall) / StepOver))
            If Not TextBoxPassesNum.Text = CStr(PassesNum) Then
                TextBoxPassesNum.BackColor = Color.Red
                TextBoxPassesNum.ForeColor = Color.White
                TextBoxPassesNum.Text = CStr(PassesNum)
            End If
        End If
        Dim IsUpside As Boolean

        '各種深さを計算
        IsUpside = Func.IsUpSideOrNot(FeatureType)
        If IsUpside Then
            StartingDepth = -((MaterialZMax - ShapeZMax) + Depth)
            TotalDepth = 0
        Else
            StartingDepth = -(MaterialZMax - ShapeZMax)
            TotalDepth = Depth
        End If

        'スタート深さのboxを変更（値を変更していれば，背景色を変更）
        If Not TextBoxStartingDepth.Text = CStr(StartingDepth) Then
            TextBoxStartingDepth.BackColor = Color.Red
            TextBoxStartingDepth.ForeColor = Color.White
            TextBoxStartingDepth.Text = CStr(StartingDepth)
        End If

        '合計深さのboxを変更（値を変更していれば，背景色を変更）
        If Not TextBoxTotalDepth.Text = CStr(TotalDepth) Then
            TextBoxTotalDepth.BackColor = Color.Red
            TextBoxTotalDepth.ForeColor = Color.White
            TextBoxTotalDepth.Text = CStr(TotalDepth)
        End If


    End Sub

    'MachiningTypeを見て MachiningModeのリストを設定/ PassesNumの変更を許可
    Private Sub ComboBoxMachiningType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBoxMachiningType.SelectedIndexChanged
        ComboBoxMachiningMode.Items.Clear()
        With ComboBoxMachiningMode
            Select Case ComboBoxMachiningType.SelectedIndex
                Case 1
                    'フェースミル加工
                    .Items.Add("")
                    .Items.Add("一方向")
                    .Items.Add("双方向")
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
                    TextBoxStockAllowanceWall.Enabled = False
                    Label1.Enabled = False
                Case 2
                    '輪郭加工
                    .Items.Add("")
                    .Items.Add("深さ方向から")
                    .Items.Add("幅方向から")
                    TextBoxPassesNum.Text = CStr(0)
                    TextBoxPassesNum.Enabled = True
                    Label17.Enabled = True
                Case 3
                    'ポケット加工
                    .Items.Add("一方向")
                    .Items.Add("ジグザグ")
                    .Items.Add("同心円-In")
                    .Items.Add("同心円-Out")
                    TextBoxPassesNum.Text = CStr(0)
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
                Case 4
                    'ドリル加工
                    .Enabled = False
                    Label4.Enabled = False
                    Label6.Enabled = False
                    Label17.Enabled = False
                    Label7.Enabled = False
                    Label9.Enabled = False
                    Label12.Enabled = False
                    Label1.Enabled = False
                    Label22.Enabled = False
                    TextBoxXYFeedrate.Enabled = False
                    ComboBoxMachiningMode.Enabled = False
                    TextBoxPassesNum.Enabled = False
                    TextBoxStepOver.Enabled = False
                    TextBoxIncrementalDepth.Enabled = False
                    ComboBoxMachiningStrategy.Enabled = False
                    TextBoxStockAllowanceWall.Enabled = False
                    TextBoxStockAllowanceFloor.Enabled = False
                Case 5
                    'スパイラル加工
                    .Items.Add("内から外")
                    .Items.Add("外から内")
                    TextBoxStepOver.Enabled = False
                    Label7.Enabled = False
                    TextBoxPassesNum.Text = CStr(0)
                    TextBoxPassesNum.Enabled = False
                    Label17.Enabled = False
            End Select
        End With
    End Sub

    'OKボタンの挙動（イベントハンドラ）
    Private Sub ButtonOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOK.Click
        AcceptMachiningData()
        Me.Close()
    End Sub

    'フォーム内の値を取得/記録
    Public Sub AcceptMachiningData()
        Dim path As String = "RoughProcessData.txt"
        Dim Write As IO.StreamWriter = New IO.StreamWriter(path)

        'フォーム内の値の取得
        MachiningType = ComboBoxMachiningType.SelectedIndex
        OperationName = TextBoxOperationName.Text
        ToolID = ButtonToolID.Text
        SpindleSpeed = CLng(TextBoxSpindleSpeed.Text)
        XYFeedrate = CDbl(TextBoxXYFeedrate.Text)
        ZFeedrate = CDbl(TextBoxZFeedrate.Text)
        MachiningMode = ComboBoxMachiningMode.SelectedIndex
        StepOver = CDbl(TextBoxStepOver.Text)
        TotalDepth = CDbl(TextBoxTotalDepth.Text)
        IncrementalDepth = CDbl(TextBoxIncrementalDepth.Text)
        StartingDepth = CDbl(TextBoxStartingDepth.Text)
        MachiningStrategy = ComboBoxMachiningStrategy.SelectedIndex
        PassesNum = CInt(TextBoxPassesNum.Text)
        StockAllowanceWall = CDbl(TextBoxStockAllowanceWall.Text)
        StockAllowanceFloor = CDbl(TextBoxStockAllowanceFloor.Text)

        'フォーム内の値の記録
        Write.Write(CStr(QueryFeatureCode) + vbCrLf)
        Write.Write(OperationName + vbCrLf)
        Write.Write(CStr(MachiningType) + vbCrLf)
        Write.Write(ToolID + vbCrLf)
        Write.Write(CStr(SpindleSpeed) + vbCrLf)
        Write.Write(CStr(XYFeedrate) + vbCrLf)
        Write.Write(CStr(ZFeedrate) + vbCrLf)
        Write.Write(CStr(MachiningMode) + vbCrLf)
        Write.Write(CStr(StepOver) + vbCrLf)
        Write.Write(CStr(TotalDepth) + vbCrLf)
        Write.Write(CStr(IncrementalDepth) + vbCrLf)
        Write.Write(CStr(StartingDepth) + vbCrLf)
        Write.Write(CStr(MachiningStrategy) + vbCrLf)
        Write.Write(CStr(PassesNum) + vbCrLf)
        Write.Write(CStr(StockAllowanceWall) + vbCrLf)
        Write.Write(CStr(StockAllowanceFloor) + vbCrLf)
        Write.Close()


        'RefDatabaseの更新
        '        path = "Ref Database.txt"
        '        Dim Read As IO.StreamReader = New IO.StreamReader(path)
        '        Dim Reader As String
        '        Dim retval(10) As String
        '        Dim DataNum As Integer = 0
        '        Dim ModelCode(100) As Integer
        '        Dim FeatureCode(100) As Integer
        '        Dim RefNum(100) As Integer
        '        Dim TotalNum(100) As Integer

        '現在までのデータを取得，値の更新
        '        While Not Read.Peek = -1
        '            Reader = Read.ReadLine
        '            retval = Reader.Split(CChar(" "))
        '            ModelCode(DataNum) = CInt(retval(0))
        '            FeatureCode(DataNum) = CInt(retval(1))
        '            RefNum(DataNum) = CInt(retval(2))
        '            TotalNum(DataNum) = CInt(retval(3))
        '            If ModelCode(DataNum) = RefModelCode And FeatureCode(DataNum) = RefFeatureCode Then
        '                RefNum(DataNum) += 1
        '            End If
        '            TotalNum(DataNum) += 1
        '            DataNum += 1
        '        End While
        '        Read.Close()

        'データの更新を書き込み
        ' Dim Write2 As IO.StreamWriter = New IO.StreamWriter(path)
        ' For i As Integer = 0 To DataNum - 1
        '     Write2.Write(CStr(ModelCode(i)) + " " + CStr(FeatureCode(i)) + " " + CStr(RefNum(i)) + " " + CStr(TotalNum(i)) + vbCrLf)
        ' Next
        ' Write2.Close()
    End Sub

    'Cancelボタンの挙動（値を取得せず終了）
    Private Sub ButtonCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonCancel.Click
        Me.Close()
    End Sub

    '工具選択ボタンを押した時の挙動（ToolSettingFormを起動）
    Private Sub ButtonToolID_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonToolID.Click
        ToolSettingForm = New ToolSettingForm
        Dim Restricting As Boolean = False
        If FeatureType = 1 Or FeatureType = 3 Or FeatureType = 4 Or FeatureType = 5 Then Restricting = True
        ToolSettingForm.Restricting(IsUsableFaceMill, IsUsableSquareEndMill, IsUsableBallEndMill, IsUsableDrill, Restricting, RestrictingLength)
        ToolSettingForm.Show()
    End Sub

    'ボタンの表示名を変更する
    Private Sub ButtonTool_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonTool.Click
        ButtonToolID.Text = ToolSettingForm.SelectedToolID
    End Sub

    '同じ加工フィーチャを検索する
    Private Sub FindSameFeature()
        Dim path As String = "Feature Data.txt"
        Dim ReaderN As StreamReader = New StreamReader(path)
        path = "Feature Database.txt"
        Dim ReaderDB As StreamReader
        Dim Read As String
        Dim retval(10) As String

        Dim FeatureNumNew As Integer
        Dim FeatureCodeNew As Integer
        Dim FeatureTypeNew As Integer

        Dim ModelCodeDB As Integer
        Dim FeatureNumDB As Integer
        Dim FeatureCodeDB As Integer
        Dim FeatureTypeDB As Integer

        gMatchNum = 0

        Read = ReaderN.ReadLine()
        retval = Read.Split(CChar(" "))

        FeatureNumNew = CInt(retval(0))

        For i As Integer = 0 To FeatureNumNew - 1
            Read = ReaderN.ReadLine
            retval = Read.Split(CChar(" "))

            FeatureCodeNew = CInt(retval(0))
            FeatureTypeNew = CInt(retval(1))

            If FeatureCodeNew = QueryFeatureCode Then
                ReaderDB = New StreamReader(path)

                Do Until ReaderDB.EndOfStream
                    Read = ReaderDB.ReadLine
                    retval = Read.Split(CChar(" "))

                    ModelCodeDB = CInt(retval(0))
                    FeatureNumDB = CInt(retval(1))

                    For j = 0 To FeatureNumDB - 1
                        Read = ReaderDB.ReadLine
                        retval = Read.Split(CChar(" "))

                        FeatureCodeDB = CInt(retval(0))
                        FeatureTypeDB = CInt(retval(1))

                        If FeatureTypeDB = FeatureTypeNew Then
                            gDBModelCode(gMatchNum) = ModelCodeDB
                            gDBFeatureCode(gMatchNum) = FeatureCodeDB
                            gMatchNum += 1
                        End If
                    Next
                Loop
                Exit For
            End If
        Next

    End Sub

    '形状類似度を計算する
    Private Sub CalShapeSimilarity()
        Dim path = "FeatureAAD.txt"
        Dim Read As String
        Dim retval(200) As String
        Dim ReaderNew As StreamReader = New StreamReader(path)
        Const AADSize As Integer = 15 * 10

        Dim FeatureNumNew As Integer
        Dim FeatureCodeNew As Integer
        Dim AADNew(AADSize) As Double

        Dim ModelCodeDB As Integer
        Dim FeatureCodeDB As Integer
        Dim FeatureNumDB As Integer
        Dim AAD_DB(100, AADSize) As Double

        '新しいモデルのAADを読み込み
        Read = ReaderNew.ReadLine
        retval = Read.Split(CChar(" "))
        FeatureNumNew = CInt(retval(0))

        For i = 0 To FeatureNumNew - 1
            Read = ReaderNew.ReadLine
            retval = Read.Split(CChar(" "))
            FeatureCodeNew = CInt(retval(0))
            If FeatureCodeNew = QueryFeatureCode Then
                For j = 1 To AADSize
                    AADNew(j - 1) = CDbl(retval(j))
                Next
                Exit For
            End If
        Next

        'DB内のAADを読み込み
        path = "AAD Database.txt"
        Dim ReaderDB As StreamReader = New StreamReader(path)

        Do Until ReaderDB.EndOfStream
            Read = ReaderDB.ReadLine
            retval = Read.Split(CChar(" "))
            ModelCodeDB = CInt(retval(0))
            FeatureNumDB = CInt(retval(1))
            '全モデルデータデータを読み込み
            For i = 0 To FeatureNumDB - 1
                Read = ReaderDB.ReadLine
                retval = Read.Split(CChar(" "))
                FeatureCodeDB = CInt(retval(0))
                For j = 0 To gMatchNum - 1
                    If gDBModelCode(j) = ModelCodeDB And gDBFeatureCode(j) = FeatureCodeDB Then   '対象のモデルかどうか
                        'AAD情報を読み込み
                        For k = 1 To AADSize
                            AAD_DB(j, k - 1) = CDbl(retval(k))
                        Next
                        Exit For
                    End If
                Next
            Next
        Loop


        Dim DisSim As Double
        '類似度の計算
        For i = 0 To gMatchNum - 1
            DisSim = 0
            For j = 0 To AADSize - 1
                DisSim += Math.Abs(AAD_DB(i, j) - AADNew(j))
            Next
            ShapeSimilarity(i) = 1.0 - 0.5 * DisSim
        Next

    End Sub

    '寸法類似度を計算
    Private Sub CalSizeSimilarity()
        Dim path = "FeatureArea.txt"
        Dim Read As String
        Dim retval(10) As String
        Dim ReaderNew As StreamReader = New StreamReader(path)

        Dim FeatureNumNew As Integer
        Dim FeatureCodeNew As Integer
        Dim AreaNew As Double

        Dim ModelCodeDB As Integer
        Dim FeatureCodeDB As Integer
        Dim FeatureNumDB As Integer
        Dim AreaDB(100) As Double

        '新しいモデルのAreaを読み込み
        Read = ReaderNew.ReadLine
        retval = Read.Split(CChar(" "))
        FeatureNumNew = CInt(retval(0))

        For i = 0 To FeatureNumNew - 1
            Read = ReaderNew.ReadLine
            retval = Read.Split(CChar(" "))
            FeatureCodeNew = CInt(retval(0))
            If FeatureCodeNew = QueryFeatureCode Then
                AreaNew = CDbl(retval(1))
                Exit For
            End If
        Next

        'DB内のAreaを読み込み
        path = "Area Database.txt"
        Dim ReaderDB As StreamReader = New StreamReader(path)

        Do Until ReaderDB.EndOfStream
            Read = ReaderDB.ReadLine
            retval = Read.Split(CChar(" "))
            ModelCodeDB = CInt(retval(0))
            FeatureNumDB = CInt(retval(1))
            '全モデルデータデータを読み込み
            For i = 0 To FeatureNumDB - 1
                Read = ReaderDB.ReadLine
                retval = Read.Split(CChar(" "))
                FeatureCodeDB = CInt(retval(0))
                For j = 0 To gMatchNum - 1
                    If gDBModelCode(j) = ModelCodeDB And gDBFeatureCode(j) = FeatureCodeDB Then   '対象のモデルかどうか
                        'Area情報を読み込み
                        AreaDB(j) = CDbl(retval(1))
                        Exit For
                    End If
                Next
            Next
        Loop

        '類似度の計算
        For i = 0 To gMatchNum - 1
            SizeSimilarity(i) = 1.0 - Math.Abs(AreaNew - AreaDB(i)) / Math.Max(AreaNew, AreaDB(i))
        Next

    End Sub

    '素材類似度を計算
    Private Sub CalMaterialSimilarity()
        Dim path = "Material.txt"
        Dim Read As String
        Dim retval(10) As String
        Dim ReaderNew As StreamReader = New StreamReader(path)

        Dim MaterialNew As Double

        Dim ModelCodeDB As Integer
        Dim FeatureCodeDB As Integer
        Dim MaterialDB(100) As Double

        '新しいモデルのMaterialを読み込み
        Read = ReaderNew.ReadLine
        retval = Read.Split(CChar(" "))

        MaterialNew = CInt(retval(0))

        'DB内のAreaを読み込み
        path = "Material Database.txt"
        Dim ReaderDB As StreamReader = New StreamReader(path)

        Do Until ReaderDB.EndOfStream
            Read = ReaderDB.ReadLine
            retval = Read.Split(CChar(" "))
            ModelCodeDB = CInt(retval(0))
            FeatureCodeDB = CInt(retval(1))
            For j = 0 To gMatchNum - 1
                If gDBModelCode(j) = ModelCodeDB And gDBFeatureCode(j) = FeatureCodeDB Then   '対象のモデルかどうか
                    'Area情報を読み込み
                    MaterialDB(j) = CDbl(retval(2))
                    Exit For
                End If
            Next
        Loop

        '類似度の計算
        For i = 0 To gMatchNum - 1
            MaterialSimilarity(i) = 1.0 - Math.Abs(MaterialNew - MaterialDB(i)) / Math.Max(MaterialNew, MaterialDB(i))
        Next


    End Sub

    '引用率の計算 140430 MEMO 現在はずべて1.0に設定
    Private Sub CalReferenceRate()
        For i As Integer = 0 To gMatchNum
            ReferencedRate(i) = 1.0
        Next
    End Sub

    '工具の使用可能性について
    Private Sub CalToolUsability()
        IsUsableFaceMill = True
        IsUsableSquareEndMill = True
        IsUsableBallEndMill = True
        IsUsableDrill = True

        Select Case FeatureType
            Case 1, 4, 2, 5, 3
                IsUsableFaceMill = False
            Case 1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 0
                IsUsableDrill = False
        End Select

        Dim path As String = "ToolOfProcess Database.txt"
        Dim Reader5 As IO.StreamReader = New StreamReader(path)
        Dim Read As String
        Dim retval(10) As String
        Dim ModelCode4T As Integer
        Dim FeatureCode4T As Integer
        Dim ToolType As Integer     '1:FaceMill/2:SquareEndMill/3:BallEndMill/4:Drill
        Dim ToolDiameter As Double
        Dim DiameterJudge As Boolean = True
        Dim DrillJudge As Boolean = False 'ドリルは完全に穴の径と工具径が一致するときのみ使用可にする．

        While Not Reader5.Peek = -1
            Read = Reader5.ReadLine
            retval = Read.Split(CChar(" "))
            ModelCode4T = CInt(retval(0))
            FeatureCode4T = CInt(retval(1))
            ToolType = CInt(retval(2))
            ToolDiameter = CDbl(retval(3))
            For i As Integer = 0 To gMatchNum
                If ModelCode4T = gDBModelCode(i) And FeatureCode4T = gDBFeatureCode(i) Then
                    DiameterJudge = True

                    If (FeatureType = 1 Or FeatureType = 3 Or FeatureType = 4 Or FeatureType = 5 Or FeatureType = 7 Or FeatureType = 8) And ToolDiameter > RestrictingLength Then DiameterJudge = False Else DiameterJudge = True
                    If (FeatureType = 7 Or FeatureType = 8) And ToolDiameter = RestrictingLength Then DrillJudge = True Else DrillJudge = False

                    Select Case ToolType
                        Case 1
                            If IsUsableFaceMill And DiameterJudge Then ToolUsability(i) = True Else ToolUsability(i) = False
                        Case 2
                            If IsUsableSquareEndMill And DiameterJudge Then ToolUsability(i) = True Else ToolUsability(i) = False
                        Case 3
                            If IsUsableBallEndMill And DiameterJudge Then ToolUsability(i) = True Else ToolUsability(i) = False
                        Case 4
                            If IsUsableDrill And DrillJudge Then ToolUsability(i) = True Else ToolUsability(i) = False
                    End Select

                    Exit For
                End If
            Next
        End While
    End Sub

    '総合類似度について
    Private Sub CalTotalSimilarity()
        'TotalSimilarityの計算
        For i As Integer = 0 To gMatchNum
            If ToolUsability(i) Then
                TotalSimilarity(i) = ReferencedRate(i) * ShapeSimilarity(i) * SizeSimilarity(i) * MaterialSimilarity(i)
            Else
                TotalSimilarity(i) = 0.0
            End If
        Next
    End Sub

    '結果のソート
    Private Sub BoubleSort()
        For i As Integer = 0 To gMatchNum - 1
            For j As Integer = gMatchNum - 1 To i + 1 Step -1
                If (TotalSimilarity(j) > TotalSimilarity(j - 1)) Then
                    Dim tModelCode As Integer = gDBModelCode(j)
                    gDBModelCode(j) = gDBModelCode(j - 1)
                    gDBModelCode(j - 1) = tModelCode

                    Dim tFeatureCode As Integer = gDBFeatureCode(j)
                    gDBFeatureCode(j) = gDBFeatureCode(j - 1)
                    gDBFeatureCode(j - 1) = tFeatureCode

                    Dim tShapeSimilarity As Double = ShapeSimilarity(j)
                    ShapeSimilarity(j) = ShapeSimilarity(j - 1)
                    ShapeSimilarity(j - 1) = tShapeSimilarity

                    Dim tSizeSimilarity As Double = SizeSimilarity(j)
                    SizeSimilarity(j) = SizeSimilarity(j - 1)
                    SizeSimilarity(j - 1) = tSizeSimilarity

                    Dim tMaterialSimilarity As Double = MaterialSimilarity(j)
                    MaterialSimilarity(j) = MaterialSimilarity(j - 1)
                    MaterialSimilarity(j - 1) = tMaterialSimilarity

                    Dim tReferencedRate As Double = ReferencedRate(j)
                    ReferencedRate(j) = ReferencedRate(j - 1)
                    ReferencedRate(j - 1) = tReferencedRate


                    Dim tToolUsability As Boolean = ToolUsability(j)
                    ToolUsability(j) = ToolUsability(j - 1)
                    ToolUsability(j - 1) = tToolUsability

                    Dim tTotalSimilarity As Double = TotalSimilarity(j)
                    TotalSimilarity(j) = TotalSimilarity(j - 1)
                    TotalSimilarity(j - 1) = tTotalSimilarity
                End If
            Next
        Next

    End Sub

End Class